/** 
 * @description 具备CRUD 操作的列表页面 ，在Rsd.view.ListDialog 基础上添加modelType和schema属性
 * @description BizController 配合使用，有规定的参数格式
 * */ 
 Rsd.define('Rsd.zen.page.BizListViewPage', {
    extend: 'Rsd.zen.page.ListViewPage',
    requires: ['Rsd.control.SearchToolBar'],
    xtype: 'biz-list-view-page', 
    readonly: false,
    form:{viewType:'Rsd.zen.dialog.BizFormDialog'},
    /**
     * @description 对象模型，用户于取Rsd.data.ModelSchema(集成了模型结构以及对象的CURD操作)对象
     * @description 优先从页面中获取，不存在时，从该页面菜单中获取
     */
    //modelType:'',
    /**
     * 对象类型结构 通过 Rsd.app.getSchema(modelType)获取
     */
    //modelSchema:null,
    /**
    *  @description 合并到父类属性 formFields后使用
    * */
    fields: [],
    /**
    *  @description 合并到父类属性 gridColumns后使用
    * */
    columns: [],
   
    /**
     *  @description 列表数据字段名
     */
    listMember:'', 
    /**
     * 
     */
    autoLoad:false,
    /**
     *  @description 工具栏上 增加的按钮
     */
    newButtons:[{text:'新 增',handler:'btn_newItem'}],
    
    /**
    * 
    * */
    constructor: function BizListViewPage(config) {
        config = config || {};
        this.apply(config); 
    },
    /**
     * 
     */
    initBySchema:function initBySchema()
    {
        var me = this;
         if(!me.modelSchema)
         {
            return;
         }
         
        if (me.searchColumns.length == 0) {
            me.searchColumns = me.modelSchema.searchColumns;
        }
        if (me.sort.length == 0) {
            me.sort = me.modelSchema.sortColumns || [];
        }

        //设计模式参数设置
        if (me.mode == 'design') {
            me.modelSchema.columns.map((p) => {
                p['design'] = true;
                p['designHandler'] = function (col) {
                    if (me.designHandler) {
                        me.funApplyByIOC(me.designHandler, ["column", col])
                    }
                    else {
                        alert('属性designHandler未设置');
                    }
                };
            }); 
        }
    },
    /**
    * */
    onBeforeInit: function onBeforeInit() {
        
        this.callParent();
          
        var me = this;
        if(!me.modelType)
        {
            return;
        }
        me.schemaIsLoading = true;
        //handler 是cqrs 对象 
        me.handler.getSchema(function (modelSchema) { 
           me.modelSchema = modelSchema; 
           me.initBySchema(); 
           me.schemaIsLoading = false;
           me.fire('schemaLoaded',[modelSchema]);
       });
         
        
        //表格和表单的schema可能不一致，如：当表格是视图，表单是table时，form和list 的schema不一致
        //加载表单schema,
        if (this.form.modelType) {

            Rsd.app.getSchema(this.form.modelType, function (modelSchema) {

                me.formSchema = modelSchema; 

                if (me.formFields.length == 0) {
                    me.formFields = modelSchema.getFields(me.fields || []);
                } 
            });
        }
  
        var curd = me.modelSchema && me.modelSchema.curd;
        if(me.formSchema)
        {
            curd = me.formSchema.curd;
        }
        if(me.readonly)
        {
            curd = 4;
        }
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
          
        var newBtns=[];
        //查询权限
        if((curd&4)===4 && me.newButtons.find(item=>item.handler == '_btn_search' || item.fn == '_btn_search')===undefined)
        {
            newBtns.push({xtype:'button', text: '查 询' ,visible:true,margin: '0 5 0 10', width: 100, handler:'_btn_search'});
        }
        //新增权限
        if((curd&1)===1 && me.newButtons.find(item=>item.handler == 'btn_newItem' || item.fn == 'btn_newItem')===undefined)
        {
            newBtns.push({ text: '新 增', handler: 'btn_newItem' });
        } 
          
        me.newButtons = Rsd.arrayConcat(newBtns,me.newButtons||[]) ; 
        for(var i in me.newButtons)
        {
            if(me.newButtons[i] == 'new'|| me.newButtons[i] =='add')
            {
                me.newButtons[i] = { text: '新 增', handler: 'btn_newItem' }; 
            }
        } 

        me.callParentFn('onBeforeInit');
   
    },
    /**
    *
    * */
    onBeforeRender: function onBeforeRender() {

        this.callParent();
  
        return this;
    },
    /*
    *
    * */
    load: function load(args,callback) {

        args = args || {};
        var me = this;
        var opt = me.getPagingOpt();
        var _args = Rsd.apply(args || {}, {
            modelType: this.modelType,
            pageSize: opt.pageSize,
            pageIndex: opt.pageIndex,
            where: Rsd.arrayConcat(args.where || [], this.where, this.toolBar && this.toolBar.getWhere()),
            sort: Rsd.arrayConcat(args.sort || [], this.sort)
        });

        if (Rsd.isEmpty(me.dataStore)) {
            var _serviceName = me.serviceName || '';
            if (Rsd.isEmpty(_serviceName) && me.modelSchema) { 
                _serviceName = me.modelSchema.listService;
            }

            if (Rsd.isEmpty(_serviceName)) {
                console.debug(me.$className, me.modelSchema || 'schema属性不存在');
                Rsd.alert("【重要】建议在打开该页面前，先获取schema\r\n未设置serviceName属性,请查看以下配置：\r\n1.页面设置属性serviceName值\r\n2.菜单设置属性serviceName值\r\n3.schema对象设置属性listService值");
                return;
            }
            me.serviceName = _serviceName;
        }

        me.callParentFn("load", [_args, callback])

        this.____lastWhere = this.toolBar && this.toolBar.getWhere();
        return this;
    },

    /**
         * 
         */
    btn_newItem:function btn_newItem(btn,evt)
    {
        this.newItem({});
    },
    /**
    * @description 查看对象
     * */
    viewItem: function viewItem(record) {
        this.showItem(record||{}, true);
    },
    /**
     * @description 新增对象
     * @param record 新增对象的默认信息
     */
    newItem:function newItem(record)
    {
        this.showItem(record||{}, false);
    },
    /**
     * @description 编辑对象
     *  */
    editItem: function editItem(record) { 
     
        this.showItem(record||{}, false);
    },
    
    /**
     * @description 删除
     * */
    deleteItem: function (record) {
        var me = this;
        if (record == null) {
            return;
        }
        me.modelSchema.deleteObject(record,function(resp){
            if (resp.success)
            {
                Rsd.popup('数据已删除');
                me.load();
            }else
            {
                Rsd.alert('数据删除失败', resp.msg);
            }
            
        }); 
    },
    /*
     * */
    itemDblClick:function itemDblClick(item,evt,config)
    { 
        if(this.readonly)
        {
            this.viewItem(item.data);
        }else
        {
            this.editItem(item.data);
        }

    }  

},function (type) {

        //formFields
        var _formFieldsGetter = function () {
            if(this.__formFields == undefined)
            {
                this.__formFields = [];
            }
            return this.__formFields;
        };

        var _formFieldsSetter = function (value) {
            this.__formFields = value;
        }

        this.defineProperty(type,"formFields", _formFieldsGetter, _formFieldsSetter,true);
        
        //modelType
        var _modelTypeGetter = function () {
 
            return this.__modelType;
        };
        var _modelTypeSetter = function (value) {

            this.__modelType = value;

        };

        //biz.list 接口参数modelType
        this.defineProperty(type,"modelType", _modelTypeGetter, _modelTypeSetter,false);

        //biz.list 接口参数sort
        this.defineProperty(type,'sort',function(){return this.__sort || [];},function(sort){
            this.__sort = sort;
        },true);

        //biz.list 接口参数where
        this.defineProperty(type,'where',function(){return this.__where||[];},function(where){
            this.__where = where;
        },true);
     
        var _handlerGetter = function () {

            if (!this.__handler) {
                this.__handler = Rsd.create('Rsd.cqrs.List', {owner: this });
            }
            return this.__handler;

        };

        var _handlerSetter = function (value) {

            if (Rsd.isString(value)) {
                this.__handler = Rsd.widget(value, {owner: this });;
                return;
            }
            this.__handler = value;
        }

        this.defineProperty(type, "handler", _handlerGetter, _handlerSetter, true);
});